package com.example.coffeeseller_2.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.example.coffeeseller_2.R;

/**
 * Created by WH on 2018/7/17.
 * 咖啡圆角图片
 */

public class CoffeeRoundImage extends android.support.v7.widget.AppCompatImageView {
    float width, height;
    float radius;
    Path path;

    public CoffeeRoundImage(Context context) {
        super(context);

    }

    public CoffeeRoundImage(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CoffeeRoundImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, @Nullable AttributeSet attrs) {
        if (Build.VERSION.SDK_INT < 18) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        path = new Path();
        TypedArray attrsArray = context.obtainStyledAttributes(attrs, R.styleable.CoffeeRoundImage);
        try {
            radius = attrsArray.getDimension(R.styleable.CoffeeRoundImage_radius, 0);
        }finally {
            attrsArray.recycle();
        }
        radius = radius * 4 / 3;//由于输入为20的时候，输出为15，输入为25时，输出为18.75，故此，保证数据与设置的一致
//        radius = DensityUtil.dp2px(context, radius);
    }

    @Override

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        super.onLayout(changed, left, top, right, bottom);

        width = getWidth();

        height = getHeight();

    }


    @Override

    protected void onDraw(Canvas canvas) {


        if (width > radius && height > radius) {



            path.moveTo(radius, 0);

            path.lineTo(width - radius, 0);

            path.quadTo(width, 0, width, radius);

            path.lineTo(width, height - radius);

            path.quadTo(width, height, width - radius, height);

            path.lineTo(radius, height);

            path.quadTo(0, height, 0, height - radius);

            path.lineTo(0, radius);

            path.quadTo(0, 0, radius, 0);

            canvas.clipPath(path);
        }


        super.onDraw(canvas);

    }

}
